<?php defined('SYSPATH') OR die('No direct access allowed.');?>
<?="<?php defined('SYSPATH') OR die('No direct access allowed.');";?>

class Generator_Model_<?=utf8::ucfirst(inflector::singular($table))?> extends ORM
{

        protected $_searched_fields = array(
<?php foreach ($fields as $f):?>
<?php if (preg_match('/string|text|varchar/i', $f['type'])) : ?>
        '<?php echo $f['name'] ?>',
<?php endif; ?>
<?php endforeach; ?>
        );

<?php if (isset($title_key)):?>
	protected $_primary_val = '<?=$title_key?>';
<?php endif ?>

        protected $_has_many = array(
        <?php foreach ($fields as $f):?>
        <?php if ($f['ref'] != '' &&  $f['ref_type'] == 'many'): ?>
        '<?php echo inflector::plural($f['ref']) ?>' => array(),
        <?php endif; ?>
        <?php endforeach; ?>
        );
        protected $_belongs_to = array(
        <?php foreach ($fields as $f):?>
        <?php if ($f['ref'] != '' &&  $f['ref_type'] == 'one'): ?>
        '<?php echo inflector::singular($f['ref']) ?>' => array(),
        <?php endif; ?>
        <?php endforeach; ?>
        );

	protected $_created_column = array('column' => 'created_at', 'format' => '<?php echo Kohana::config('app.date_format')?>');
        protected $_updated_column = array('column' => 'updated_at', 'format' => '<?php echo Kohana::config('app.date_format')?>');

        protected $_filters = array(
            TRUE       => array('trim' => array()),
        );

        protected $_rules = array(
        <?php foreach ($fields as $f):?>
        '<?php echo $f['name'] ?>' => array(
                <?php if (! $f['null']): ?>
                    'not_empty' => array(),
                <?php endif; ?>
                <?php if (strpos($f['name'], 'email') !== FALSE) :?>
                    'email' => array(),
                <?php endif; ?>
        ),
        <?php endforeach; ?>
        );

        protected $_callbacks = array(
        <?php foreach ($fields as $f):?>
        <?php if ($f['uniq']): ?>
'<?php echo $f['name'] ?>' => array('<?php echo $f['name'] ?>_unique'),
        <?php endif; ?>
        <?php endforeach; ?>
        );

        <?php foreach ($fields as $f):?>
            <?php if ($f['uniq']): ?>
public function <?php echo $f['name'] ?>_unique(Validate $data, $field)
        {
            $res = (bool) DB::select(array('COUNT("*")', 'total_count'))
			->from($this->_table_name)
			->where('<?php echo $f['name'] ?>', '=', $data[$field])
			->where($this->_primary_key, '!=', $this->pk())
			->execute($this->_db)
			->get('total_count');

            if ($res)
                $data->error($field, '<?php echo $f['name'] ?>_unique', array($data[$field]));
        }
            <?php endif; ?>
        <?php endforeach; ?>

        <?php foreach ($fields as $f):?>
        <?php if ($f['ref'] != '' &&  $f['ref_type'] == 'one'): ?>
        public static function get_by_<?php echo $f['name'] ?>($<?php echo $f['name'] ?>_id)
        {
            return $this
                    ->where('<?php echo $f['name'] ?>', '=', $<?php echo $f['name'] ?>_id)
                    ->find_all();
        }
        <?php endif; ?>
        <?php endforeach; ?>

        public static function get_list($filter=array(), $search='', $sort='', $desc=false, $limit=0, $offset=false, &$count=0)
        {
            $query = ORM::factory('<?php echo inflector::singular($table) ?>');

            if (is_array($filter))
            {
                foreach ($array as $key => $value)
                {
                    $query = $query->where($key, '=', $value);
                }
            }

            if ($search != '')
            {
                foreach ($this->_searched_fields as $f)
                {
                    $query = $query->where($f, 'like', '%'.$search.'%');
                }
            }

            if ($sort != '')
            {
                $query = $query->order_by(array($sort => ($desc ? 'asc': 'desc')));
            }

            $count = $query->reset(FALSE)->count_all();

            if ($limit > 0) $query = $query->limit($limit);
            if ($offset != false) $query = $query->offset($offset);

            return $query->find_all();
        }

        /**
	 * Returns the value of the primary val
	 *
	 * @return  mixed  primary val
	 */
	public function tk()
	{
            return $this->_object[$this->_primary_val];
	}
}